package com.mystore.author.security.web.filter;

import com.mystore.framework.pojo.LoginUser;
import com.mystore.framework.pojo.User;
import com.mystore.framework.service.impl.AuthorRedisServiceImpl;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * 过滤器，如果登录了就行
 */
public class ApplicationWebFilter extends OncePerRequestFilter {
    @Resource
    private AuthorRedisServiceImpl authorRedisServiceImpl;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpSession session=request.getSession();
        String userId= String.valueOf(session.getAttribute("userId"));
        if(!StringUtils.hasText(userId)){
            filterChain.doFilter(request,response);
            return;
        }
        String redisKey = "user-id-" + userId;
        LoginUser loginUser = (LoginUser) authorRedisServiceImpl.get(redisKey);
        if(Objects.isNull(loginUser)){
            SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key","anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
            filterChain.doFilter(request,response);
            return;
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}